import os

filename = 'students.txt'

def menu():
    print('''
    学生信息管理系统
    ========== 功能菜单 =============

    1 录入学生信息
    2 查找学生信息
    3 删除学生信息
    4 修改学生信息
    5 排序
    6 统计学生总人数
    7 显示所有学生信息
    8 退出系统
    
    ========== 功能菜单 =============
    ''')

def main():
    isExit = True
    while(isExit):
        menu()
        option = input('请选择:')
        if option in ['1','2','3','4','5','6','7','8']:
            option_int = int(option)
            if option_int == 8:
                print('您已经退出学生信息管理系统！')
                isExit = False
            elif option_int == 1:
                insert()
            elif option_int == 2:
                search()
            elif option_int == 3:
                delete()
            elif option_int == 4:
                modify()
            elif option_int == 5:
                sort()
            elif option_int == 6:
                total()
            elif option_int == 7:
                show()
        else:
            print('您已经退出学生信息管理系统！')
            isExit = False

def insert():
    studentList = []
    isInsert = True
    while isInsert:
        id = input('请输入ID（如 1001）：')
        if not id:
            break
        name = input('请输入名字：')
        if not name:
            break
        try:
            yuwen = int(input('请输入语文成绩：'))
            shuxue = int(input('请输入数学成绩：'))
            english = int(input('请输入英语成绩：'))
        except:
            print('输入无效，不是数字类型……请重新录入信息')
            continue
        student = {'id':id,'name':name,'yuwen':yuwen,'shuxue':shuxue,'english':english}
        studentList.append(student)
        isMore = input('是否继续添加？（y/n）：')
        if isMore == 'y':
            isInsert = True
        else:
            isInsert = False
    save(studentList)
    print('学生信息录入完毕！')

def save(student):
    try:
        students_txt = open(filename,'a')
    except:
        students_txt = open(filename,'w')
    for info in student:
        students_txt.write(str(info) + '\n')
    students_txt.close()

def search():
    isSearch = True
    student_query = []
    while isSearch:
        id = ''
        name = ''
        if os.path.exists(filename):
            mode = input('按ID查询请输入1；按姓名查询请输入2：')
            if mode == '1':
                id = input('请输入学生ID：')
            elif mode == '2':
                name = input('请输入学生姓名：')
            else:
                print('您的输入有误，请重新输入！')
                continue
            with open(filename,'r') as file:
                student = file.readlines()
                for list in student:
                    d = dict(eval(list))
                    if id is not '':
                        if d['id'] == id:
                            student_query.append(d)
                    if name is not '':
                        if d['name'] == name:
                            student_query.append(d)
                show_student(student_query)
                student_query.clear()
                inputMark = input('是否继续查询？（y/n）：')
                if inputMark == 'y':
                    isSearch = True
                else:
                    isSearch = False
        else:
            print('暂未保存数据信息……')

def show_student(studentList):
    if not studentList:
        print('无数据信息 \n')
        return
    format_title = "{:^6}{:^12}{:^8}{:^10}{:^10}{:^10}"
    print(format_title.format("ID","姓名","语文","数学","英语","总成绩"))
    format_data =  "{:^6}{:^12}{:^12}{:^12}{:^12}{:^12}"
    for info in studentList:
        print(format_data.format(info.get('id'),info.get('name'),info.get('yuwen'),
                                 info.get('shuxue'),info.get('english'),
                                 float(info.get('yuwen'))+float(info.get('shuxue'))+float(info.get('english'))))


def delete():
    mark = True
    while mark:
        studentId = input('请输入要删除的学生ID：')
        if studentId is not '':
            if os.path.exists(filename):
                with open(filename,'r') as rfile:
                    student_old = rfile.readlines()
            else:
                student_old = []
            isdel = False
            if student_old:
                with open(filename,'w') as wfile:
                    d = {}
                    for list in student_old:
                        d = dict(eval(list))
                        if d['id'] != studentId:
                            wfile.write(str(d) + '\n')
                        else:
                            isdel = True
                    if isdel:
                        print('ID 为%s的学生信息已经被删除……'% studentId)
                    else:
                        print('没有找到ID 为%s的学生信息……'% studentId)
            else:
                print('无学生信息……')
                break
            show()
            isMore = input('是否继续删除？（y/n）：')
            if isMore == 'y':
                mark = True
            else:
                mark = False

def show():
    student_new = []
    if os.path.exists(filename):
        with open(filename,'r') as rfile:
            student_old = rfile.readlines()
        for list in student_old:
            student_new.append(eval(list))
        if student_new:
            show_student(student_new)

def modify():
    show()
    if os.path.exists(filename):
        with open(filename,'r') as rfile:
            student_old = rfile.readlines()
    else:
        return
    studentId = input('请输入要修改的学生ID：')
    with open(filename,'w') as wfile:
        d = {}
        for student in student_old:
            d = dict(eval(student))
            if d["id"] == studentId:
                print("修改这名学生的信息！")
                while True:
                    try:
                        d["name"] = input("请输入姓名：")
                        d["yuwen"] = input("请输入语文成绩：")
                        d["shuxue"] = input("请输入数学成绩：")
                        d["english"] = input("请输入英语成绩：")
                    except:
                        print("您的输入有误，请重新输入。")
                    else:
                        break
                student = str(d)
                wfile.write(student +"\n")
                print("修改成功！")
            else:
                student = str(d)
                wfile.write(student+"\n")
        mark = input("是否继续修改其他学生信息？（y/n）：")
        if mark == 'y':
            modify()

def sort():
    show()
    if os.path.exists(filename):
        with open(filename,'r') as rfile:
            student_old = rfile.readlines()
        student_new = []
        for list in student_old:
            d = dict(eval(list))
            student_new.append(d)
    else:
        return
    asc = input("请选择(0升序；1降序)：")
    if asc == "0":
        asc = False
    else:
        asc = True
    mode = input("请选择排序方式（1语文成绩；2数学成绩；3英语成绩；0总成绩）：")
    if mode == "1":
        student_new.sort(key=lambda x:float(x["yuwen"]),reverse = asc)
    elif mode == "2":
        student_new.sort(key=lambda x:float(x["shuxue"]),reverse = asc)
    elif mode == "3":
        student_new.sort(key=lambda x:float(x["english"]),reverse = asc)
    elif mode == "0":
        student_new.sort(key=lambda x:float(x["yuwen"])+float(x["shuxue"])+float(x["english"]),reverse = asc)
    else:
        print("您的输入有误，请重新输入！")
        sort()
    show_student(student_new)

def total():
    if os.path.exists(filename):
        with open(filename,'r') as rfile:
            student_old = rfile.readlines()
            if student_old:
                print("一共有%d名学生" % len(student_old))
            else:
                print("还没有录入学生信息")
    else:
        print("暂未保存数据信息……")

